import CryptoJS from 'crypto-js'
import {JSEncrypt} from "jsencrypt";

export default {
    // 随机生成指定数量的16进制key
    signByRequest(nonce, timestamp) {
    let buffer = null;
    if ((parseInt(nonce.length) & 1) === 1) {
        buffer = nonce.toString() + timestamp.toString();
    } else {
        buffer = timestamp.toString() + nonce.toString();
    }
    return CryptoJS.MD5("localhost" + buffer + "127.0.0.1").toString();
    },
    // 加密
    AesEncrypt (word, keyStr) {
        var key = CryptoJS.enc.Utf8.parse(keyStr)
        var encryptedData = CryptoJS.AES.encrypt(word, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        })
        return CryptoJS.enc.Base64.stringify(encryptedData.ciphertext)
    },
    // 解密
    AesDecrypt (word, keyStr) {
        keyStr = keyStr || null
        var key = CryptoJS.enc.Utf8.parse(keyStr)
        var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
        return CryptoJS.enc.Utf8.stringify(decrypt).toString()
    },
    RSAEncrypt (word, publicKey) {
        var encrypt = new JSEncrypt()
        encrypt.setPublicKey(publicKey)
        return encrypt.encrypt(word)
    }
}
